package com.lincoln.framework.service;

import com.lincoln.framework.entity.SysAdmin;
import com.lincoln.framework.hibernate.Page;
import com.lincoln.framework.hibernate.SimpleHibernateTemplate;
import com.lincoln.framework.utils.ParameterChecker;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 系统管理员service
 * 
 * @author zwm
 */
@Service
@Transactional
public class SysAdminService {
	
	@Autowired
	private SysAdminLogService sysAdminLogsService;

	private SimpleHibernateTemplate<SysAdmin, Integer> sysAdminDao;

	@Autowired
	public void setSessionFactory (SessionFactory sessionFactory) {
		sysAdminDao = new SimpleHibernateTemplate<SysAdmin, Integer>(sessionFactory, SysAdmin.class);
	}

	/**
	 * 根据账号密码查找系统管理员信息
	 */
	public SysAdmin getSysAdminByNameAndPassword (String name, String md5Password) {
		List<SysAdmin> admins = sysAdminDao.findByCriteria(Restrictions.eq("name", name),
				Restrictions.eq("md5Password", md5Password));
		if (admins == null || admins.size() == 0) {
			return null;
		}
		return admins.get(0);
	}

	/**
	 * 保存系统管理员信息
	 * 
	 * @param admin
	 *            void
	 */
	public void saveSysAdmin (SysAdmin admin) {
		this.sysAdminDao.save(admin);
	}

	/**
	 * 根据id获取系统管理员信息
	 * 
	 * @param id
	 *            void
	 */
	public SysAdmin getSysAdminById (int id) {
		return this.sysAdminDao.get(id);
	}
	
	/**
	 * 根据name获取系统管理员信息
	 *
	 *            void
	 */
	public SysAdmin getSysAdminByName (String name) {
		return sysAdminDao.findUnique(Restrictions.eq("name", name));
	}
	
	public Page<SysAdmin> getSysAdminPage(Page<SysAdmin> page) {
		Criteria c = sysAdminDao.createCriteria();
		Map<String, Object> queryMap = page.getQueryMap();
		if (!ParameterChecker.isNullOrEmpty((String) queryMap.get("realName"))) {
			c.add(Restrictions.like("realName", (String)queryMap.get("realName"), MatchMode.ANYWHERE));
		}
		if (!ParameterChecker.isNullOrEmpty((String)queryMap.get("name"))) {
			c.add(Restrictions.like("name", (String)queryMap.get("name"), MatchMode.ANYWHERE));
		}
		if (!ParameterChecker.isNullOrEmpty((String)queryMap.get("roleId")) && !queryMap.get("roleId").equals("0")) {
			c.add(Restrictions.eq("sysRole.id", Integer.valueOf((String)queryMap.get("roleId"))));
		}
		page = sysAdminDao.findByCriteria(page, c);
		return page;
	}
	
	/**
	 * 删除系统管理员信息
	 * 
	 * @param admin
	 *            void
	 */
	public void deleteSysAdmin (SysAdmin admin) {
		sysAdminLogsService.deleteSysAdminLogByAdminId(admin);
		this.sysAdminDao.delete(admin);
	}
}
